<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import * as CustomerApi from '@src/api/CustomerApi';

/* utils */
import _ from 'lodash';
import * as Utils from '@src/component/form/util';

/* components */
import {
  FormFieldMap,
  SettingComponents,
} from '@src/component/form/components';
import SearchProductSelect from './SearchProductSelect.vue';
import SearchCustomerSelect from './SearchCustomerSelect.vue';

export default {
  name: 'search-form',
  props: {
    searchList: {
      type: Array,
      default: () => [], // 搜索值
    },
    formBackup: {
      type: Object,
      default: () => ({}),
    },
    columnNum: {
      type: Number,
      default: 1, // 一栏二栏
    },
  },
  data() {
    return {
      customer: {},
      form: {},
      product: {},
    };
  },
  computed: {
    fields() {
      let f = {};
      let fields = this.searchList.map(field => {
        f = _.cloneDeep(field);

        let formType = f.formType;

        if (formType === 'datetime') {
          formType = 'date';
        }

        if (f.fieldName === 'customer') {
          formType = 'customer';
        }

        if (formType === 'updateTime') {
          f.displayName = this.$t('task.list.displayName.updateTime');
        }
        return Object.freeze({
          ...f,
          isNull: 1,
          formType,
          originalFormType: f.formType,
          operator: this.matchOperator(f)
        });
      })
        .sort((a, b) => a.orderId - b.orderId);
        
      return fields;
    },
  },
  watch: {
    fields() {
      this.buildForm();
    },
  },
  created() {
    this.buildForm();
  },
  methods: {
    buildForm() {
      if (Object.keys(this.form).length === this.fields.length) return;
      this.initFormVal();
    },

    createUserInput(event, isTags) {
      if (isTags) {
        return (this.form.tags = event);
      }
      const f = event.field;
      this.form[f.fieldName] = event.keyword;
    },

    // 默认值初始化为对象
    initFormVal() {
      let fields = this.fields;
      let form = {};
      let tv = '';
      fields.forEach((field) => {
        tv = '';
        if (field.formType == 'customerAddress' || field.formType == 'address')
          tv = {};
        if (field.formType == 'date' || field.formType == 'datetime') tv = [];
        if (field.formType === 'link') {
          tv = {};
        }
        if (field.fieldName === 'tags') {
          tv = [];
        }
        if (field.formType === 'area' || field.formType === 'cascader') {
          tv = [];
        }

        if (field.formType === 'user') {
          tv = [];
        }

        form[field.fieldName] = this.formBackup[field.fieldName] || tv;
        this.$set(
          this.form,
          field.fieldName,
          this.formBackup[field.fieldName] || tv
        );
      });

      let backUp = this.formBackup.backUp || {};
      this.$set(this, 'customer', backUp.customer || {});
      this.$set(this, 'product', backUp.product || {});

      return form;
    },

    // 操作符
    matchOperator(field) {
      let formType = field.formType;
      let operator = '';

      switch (formType) {
      case 'date': {
        operator = 'between';
        break;
      }
      case 'datetime': {
        operator = 'between';
        break;
      }
      case 'select': {
        if (field.setting && field.setting.isMulti) {
          operator = 'contain';
        } else {
          operator = 'eq';
        }
        break;
      }
      case 'user': {
        operator = 'user';
        break;
      }
      case 'cascader': {
        operator = 'cascader';
        break;
      }
      case 'address': {
        operator = 'address';
        break;
      }
      case 'location': {
        operator = 'location';
        break;
      }
      default: {
        operator = 'like';
        break;
      }
      }
      return operator;
    },

    // render 值渲染
    renderInput(h, field) {
      const f = _.cloneDeep(field);
      let comp = FormFieldMap.get(f.formType);
      if (!comp || f.formType === 'area') {
        return null;
      }

      let childComp = null;

      if (f.fieldName == 'customer') {
        let value = this.form[f.fieldName];
        childComp = h('search-customer-select', {
          props: {
            placeholder: this.$t('common.placeholder.selectCustomer'),
            field: f,
            value: value ? [{ label: this.customer.name || '', value }] : [],
            remoteMethod: this.searchCustomer,
          },
          on: {
            input: (event) => {
              this.customer = event && event.length > 0 ? event[0] : {};
              this.form[f.fieldName] = this.customer.id;
            },
          },
        });
      } else if (f.fieldName == 'product') {
        let value = this.form[f.fieldName];
        childComp = h('search-product-select', {
          props: {
            placeholder: this.$t('common.placeholder.selectProduct'),
            field: f,
            value: value ? [{ label: this.product.name || '', value }] : [],
            remoteMethod: this.searchProduct,
          },
          on: {
            input: (event) => {
              this.product = event && event.length > 0 ? event[0] : {};
              this.form[f.fieldName] = this.product.id;
            },
          },
        });
      } else if (f.formType === 'user') {
        childComp = h('user-search', {
          props: {
            field: f,
            value: this.form[f.fieldName],
            disableMap: true,
          },
          on: {
            update: (event) => this.update(event),
          },
        });
      } else if (f.fieldName === 'tags') {
        let value = this.form[f.fieldName];
        childComp = h('biz-team-select', {
          props: {
            value: value || [],
          },
          on: {
            input: (event) => this.update(event, 'tags'),
          },
        });
      } else if (f.fieldName === 'tlmName') {
        f.clearable = true;
        childComp = h('linkman-search', {
          props: {
            field: f,
            value: this.form[f.fieldName],
            disableMap: true,
          },
          on: {
            update: (event) => this.update(event),
          },
        });
      } else {
        childComp = h(
          comp.extend && comp.extend[`${f.formType}_search`]
            ? comp.extend[`${f.formType}_search`]
            : comp.build,
          {
            props: {
              field: f,
              value: this.form[f.fieldName],
              disableMap: true,
              placeholder: Utils.genPlaceholder(f),
              seo: true,
              toggle: true
            },
            on: {
              update: (event) => this.update(event),
            },
          }
        );
      }
      return h(
        'form-item',
        {
          props: {
            label: f.displayName,
            needValidate: false,
          },
        },
        [childComp]
      );
    },

    // return 选中的值
    returnData() {
      let data = {};
      for(let key in this.form) {
        let value = this.form[key]
        if (value && JSON.stringify(value) !== '[]' && JSON.stringify(value) !== '{}') {
          data[key] = value
        }
      }
      return {data};
    },

    // 客户render
    searchCustomer(params) {
      const pms = params || {};

      return CustomerApi.getCustomerListAsyn(pms)
        .then((res) => {
          if (!res || !res.list) return;

          res.list = res.list.map((custoner) =>
            Object.freeze({
              label: custoner.name,
              value: custoner.id,
              ...custoner,
            })
          );
          return res;
        })
        .catch((e) => console.error(e));
    },

    // 产品内容
    searchProduct(params) {
      const pms = params || {};

      pms.customerId = this.form.customer || '';
      return TaskApi.getTaskCustonerProductList(pms)
        .then((res) => {
          if (!res.result || !res.result?.list) return;
          res.result.list = res.result.list.map((product) =>
            Object.freeze({
              label: product.name,
              value: product.id,
              ...product,
            })
          );
          return res.result;
        })
        .catch((e) => console.error(e));
    },

    // 筛选的值
    update(event, action) {
      if (action === 'tags') {
        return (this.form.tags = event);
      }

      if (action === 'dist') {
        return (this.form.area = event);
      }
      const f = event.field;
      this.form[f.fieldName] = event.newValue;
    },

  },
  render(h) {
    return (
      <div
        class={`form-item-container ${
          this.columnNum == 2 ? 'two-columns' : ''
        }`}
      >
        {this.fields.map((f) => this.renderInput(h, f))}
      </div>
    );
  },
  components: {
    ...SettingComponents,
    [SearchProductSelect.name]: SearchProductSelect,
    [SearchCustomerSelect.name]: SearchCustomerSelect,
  },
};
</script>
<style lang="scss" scoped>
    .form-item-container {
        margin-top: 12px;
    }
    .two-columns {
      display: flex;
      flex-wrap: wrap;
      .form-item {
        width: 50%;
      }
    }
</style>